package com.colorful.insuranceproject.request;

import android.support.annotation.NonNull;

import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.colorful.insuranceproject.bean.UserInfo;
import com.colorful.insuranceproject.consts.CodeTable;
import com.colorful.insuranceproject.consts.URLConst;
import com.litesuits.orm.db.assit.QueryBuilder;
import com.lovely3x.common.beans.LocationWrapper;
import com.lovely3x.common.managements.LocationManager;
import com.lovely3x.common.managements.user.IUser;
import com.lovely3x.common.managements.user.TokenManager;
import com.lovely3x.common.managements.user.UserManager;
import com.lovely3x.common.utils.ALog;
import com.lovely3x.common.utils.Response;
import com.lovely3x.jsonparser.model.JSONObject;
import com.lovely3x.loginandresgiter.login.SimpleLander;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 登录器
 * Created by lovely3x on 16/8/4.
 */
public class Lander extends SimpleLander {

    private static final Random random = new Random();

    private static final int LOGIN_OUT = 0X1;

    private final UserRequest mUserRequest;

    public Lander() {
        this.mUserRequest = new UserRequest(null);
    }

    /**
     * 登录的what
     */
    private int LOGIN_WHAT = Integer.MAX_VALUE;

    @Override
    public int login(@NonNull IUser user) {

        /* String model = android.os.Build.MODEL;
         ALog.e(TAG, "获取手机型号：" + model);
         String carrier = android.os.Build.MANUFACTURER;
         ALog.e(TAG, "获取手机厂商：" + carrier);**/
        if (user instanceof UserInfo) {
            if (LOGIN_WHAT != Integer.MAX_VALUE) {
                cancelLogin();
            }
            //获取位置
            LocationManager.getInstance().start();
            LocationWrapper loc = LocationManager.getInstance().getCurrentLocation();
            //如果没有获取到就使用默认的
            if (loc == null) loc = new LocationWrapper();

            UserInfo simpleUser = (UserInfo) user;
            CloudPushService pushService = PushServiceFactory.getCloudPushService();
            Response result = processSync(URLConst.LOGIN_URL, LOGIN_WHAT,
                    "userPhone", simpleUser.getPhone(),
                    "loginKey", simpleUser.getPassword(),
                    "mobileCode", simpleUser.getInviteCode(),
                    "messageId", simpleUser.getUserInformation(),
                    "loginRemark", "android",
                    "deviceId", android.os.Build.MODEL,
                    "jpushtag", pushService.getDeviceId());
            if (result.isSuccessful) {
                LocationManager.getInstance().stop();
                JSONObject jo = new JSONObject(String.valueOf(result.obj));
                // 获取Token
                String token = jo.getJSONObject(DATA_KEY).getString(TOKEN_KEY);
                // 存储TokenId
                simpleUser.setToken(token);

                simpleUser.setUserName(jo.getJSONObject(DATA_KEY).getString("userName"));

                simpleUser.setIdCard(jo.getJSONObject(DATA_KEY).getString("idCard"));

                simpleUser.setBankCard(jo.getJSONObject(DATA_KEY).getString("cardNumber"));

                simpleUser.setPayPwd(jo.getJSONObject(DATA_KEY).getString("payPwd"));

                simpleUser.setUid(jo.getJSONObject(DATA_KEY).getString("userId"));

                pushService.bindAccount(simpleUser.getUid(), null);

                simpleUser.setPhone(Long.parseLong(jo.getJSONObject(DATA_KEY).getString("userPhone")));

//                "tokenId": "f09051375d8744d5aa1c2a167be121f8",
//                        "idCard": "51052119850508797X",
//                        "userPhone": "13588003937",
//                        "payPwd": "1",
//                        "bankName": "招商银行杭州市滨江支付",
//                        "userName": "唐丽er",
//                        "userId": 248516,
//                        "cardNumber": "6214830157447052"

                // Update token
                TokenManager.getInstance().setTokenValue(token);
                // 设置上次登陆时间
                simpleUser.setLastLoginTime(System.currentTimeMillis());

                // 登录成功
                if (result.isSuccessful) {
                    ALog.i(TAG, "User info => " + result);
                    mUserRequest.updateUserInfoSync(user);
                    return 0;
                }
            }
            //登录失败
            LocationManager.getInstance().stop();
            return result.errorCode;
        }
        return CodeTable.getInstance().getUnknownErrorCode();
    }

    /**
     * 退出
     */
    @Override
    public int logout(@NonNull IUser user) {
        if (UserManager.getInstance().isSigned()) {
            if (UserManager.getInstance().getCurrentUser() instanceof UserInfo) {
                mUserRequest.loginOut(LOGIN_OUT);
                user.setState(IUser.STATE_OFFLINE);
                updateOrInsertUser(user);
            } else {
                return CodeTable.UNSUPPORTED_USER;
            }
        }
        return super.logout(user);
    }

    @NonNull
    @Override
    public List<IUser> getAllUserFromDatabases() {
        synchronized (SimpleLander.class) {
            ArrayList<?> result = getOrm().query(UserInfo.class);
            return (List<IUser>) result;
        }
    }

    @Override
    public IUser getLastUser() {
        synchronized (SimpleLander.class) {
            ArrayList<UserInfo> list = getOrm().query(QueryBuilder.create(UserInfo.class).appendOrderDescBy("_last_login_time"));
            if (list != null && !list.isEmpty()) {
                return list.get(0);
            }
        }
        return null;
    }

    @Override
    public void cancelLogin() {
        if (LOGIN_WHAT != Integer.MAX_VALUE) {
            cancelTask(LOGIN_WHAT);
            LOGIN_WHAT = Integer.MAX_VALUE;
        }
    }
}
